import { find } from "@/api/modules/find";

export const getDicFromApi = (key) =>
  find.groupResource.dic().then(({data}) => {
    try {
      localStorage.setItem("dict", JSON.stringify(data));
    } catch (e) {
      // error
    }
    return key ? data[key] : data;
  });

export const getDicItemAsync = (key) => {
  return new Promise((resolve, reject) => {
    const data = localStorage.getItem("dict") || {};
    const dicAll = JSON.parse(data);
    if (dicAll) {
      resolve(key ? dicAll[key] : dicAll);
    } else {
      getDicFromApi(key).then((data) => {
        resolve(data);
      });
    }
  });
};

export const getDicItem = (key) => {
  const data = localStorage.getItem("dict") || {};
  const dicAll = JSON.parse(data);
  return key ? dicAll[key] : dicAll || [];
};

export const getDicItemMap = (key) => {
  return new Promise((resolve, reject) => {
    getDicItemAsync(key).then((data) => {
      const dataMap = data.reduce((init, item) => {
        init[item.code] = item.name;
        return init;
      }, {});
      resolve(dataMap);
    });
  });
};
